//
//  ACThemeManager.swift
//  ACFrameworkSwift
//
//  Created by c5342925 on 2022/3/23.
//

import Foundation
import UIKit

public typealias ACThemeDynamicProviderClosure<T> = (ACThemeStyle) -> T?

extension Notification.Name {
    static let ThemeDidChange = Notification.Name("ACFrameworkSwift.ThemeDidChange")
}


/// Manager for the theme.
public class ACThemeManager {
    
    public static let share = ACThemeManager()
    
    public var currentTheme: ACThemeStyle = .light
    
    public func switchTheme(theme: ACThemeStyle) {
        guard currentTheme != theme else { return }
        currentTheme = theme
        NotificationCenter.default.post(name: .ThemeDidChange, object: nil)
    }
}


/// The type of all themes.
public enum ACThemeStyle {
    case light
    case dark
    
    public var type: ACPaletteProvider {
        switch self {
        case .light:
            return LightTheme()
        case .dark:
            return DarkTheme()
        }
    }
}


/// Add observer for system trait collection, receive the switch of system dark mode.
class ThemeWindow: UIWindow {
    
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        if #available(iOS 13.0, *) {
            guard previousTraitCollection?.userInterfaceStyle != UITraitCollection.current.userInterfaceStyle else {
                return
            }
            let isDark = UITraitCollection.current.userInterfaceStyle == .dark
            ACThemeManager.share.switchTheme(theme: isDark ? .dark : .light)
        }
    }
}
